package com.xxx.shetuan3.exception;
import com.xxx.shetuan3.common.CommonResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.SocketTimeoutException;

/**
 * 全局异常处理器
 *
 * @author RuL
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义API异常
     *
     * @param e 自定义API异常
     * @return 失败类返回结果
     */
    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public CommonResult handle(ApiException e) {
        if (e.getResultCode() != null) {
            return CommonResult.failed(e.getResultCode());
        }
        return CommonResult.failed(e.getMessage());
    }

    /**
     * 参数错误异常处理
     *
     * @param e 参数错误异常
     * @return 参数校验失败返回结果
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return CommonResult.validateFailed(message);
    }

    /**
     * 数据类型不匹配异常处理
     *
     * @param e 数据类型不匹配异常
     * @return 参数校验失败返回结果
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public CommonResult handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return CommonResult.validateFailed(message);
    }

    /**
     * 数据类型不匹配异常处理
     *
     * @param e 数据类型不匹配异常
     * @return 参数校验失败返回结果
     */
    @ResponseBody
    @ExceptionHandler(value = SocketTimeoutException.class)
    public CommonResult handleValidException(SocketTimeoutException e) {
        return CommonResult.validateFailed("请求超时");
    }
}
